package org.kl.bf.service.workflow;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.activiti.engine.identity.Group;
import org.activiti.engine.impl.GroupQueryImpl;
import org.activiti.engine.impl.Page;
import org.activiti.engine.impl.persistence.entity.GroupEntity;
import org.activiti.engine.impl.persistence.entity.GroupEntityManager;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.kl.bf.entity.basic.Role;
import org.kl.bf.service.basic.AccountService;
import org.kl.bf.service.basic.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Service;

/**
 * @Author hqm
 * @CreateTime 2014年5月13日 上午8:35:16
 */
@Service
public class CustomGroupEntityManager extends GroupEntityManager {
	@SuppressWarnings("unused")
	private static final Log logger = LogFactory.getLog(CustomGroupEntityManager.class);

	@Autowired
	private AccountService accountService;
	@Autowired
	private RoleService roleService;

	public GroupEntity findGroupById(final String roleNo) {
		if (roleNo == null)
			return null;
		try {
			Role role = roleService.getRoleByRoleNo(roleNo);
			GroupEntity e = new GroupEntity();
			e.setRevision(1);

			// activiti有3种预定义的组类型：security-role、assignment、user
			// 如果使用Activiti
			// Explorer，需要security-role才能看到manage页签，需要assignment才能claim任务
			e.setType("assignment");
			e.setId(role.getRoleNo());
			e.setName(role.getRoleName());
			return e;
		} catch (EmptyResultDataAccessException e) {
			return null;
		}
	}

	@Override
	public List<Group> findGroupsByUser(final String loginNo) {
		if (loginNo == null)
			return null;
		Set<Role> roleList = accountService.findUserByLoginNo(loginNo).getRoleSet();
		List<Group> gs = new ArrayList<Group>();
		GroupEntity g;
		for (Role role : roleList) {
			g = new GroupEntity();
			g.setRevision(1);
			g.setType("assignment");
			g.setId(role.getRoleNo());
			g.setName(role.getRoleName());
			gs.add(g);
		}
		return gs;
	}

	@Override
	public List<Group> findGroupByQueryCriteria(GroupQueryImpl query, Page page) {
		throw new RuntimeException("not implement method.");
	}

	@Override
	public long findGroupCountByQueryCriteria(GroupQueryImpl query) {
		throw new RuntimeException("not implement method.");
	}
}
